import React, {Component} from 'react'
import {
    DeviceEventEmitter,
    Dimensions,
    Image,
    ListView,
    Platform,
    RefreshControl,
    ScrollView,
    StyleSheet,
    Text,
    TouchableOpacity,
    View,
    WebView,
} from "react-native";
import GoodsRender from "../../utils/GoodsRender";
import ParallaxScrollView from 'react-native-parallax-scroll-view';
import ViewUtils from "../../utils/ViewUtils";
import StyleUtils from "../../res/styles/StyleUtils";
import Carousel from 'react-native-banner-carousel';
import CommonUtils, {getFormatDate} from "../../common/CommonUtils";

import AddToCartModal from "../../utils/AddToCartModal";
import IparNetwork, {IMAGE_URL, SERVER_TYPE} from "../../httpUtils/IparNetwork";
import RegionsIcon from "../../common/RegionsIcon";
import LoginPage from "./LoginPage";
import AlertDialog from "../../custom/AlertDialog";
import I18n from "../../res/language/i18n";
import MyWebView from 'react-native-webview-autoheight';
import ModalBottomUtils from "../../utils/ModalBottomUtils";
import SubAccountsPage from "../mePage/business/SubAccountsPage";
import IparImageView from "../../custom/IparImageView";

const {width} = Dimensions.get('window');

let clickTypes = {collection: 'collection'};
let ds = new ListView.DataSource({
    rowHasChanged: (row1, row2) => row1 !== row2,
});
export default class GoodsPage extends Component {
    // 构造
    constructor(props) {
        super(props);
        // 初始状态

        this.iparNetwork = new IparNetwork();
        this.commonUtils = new CommonUtils();
        this.country = '';
        this.goodsNumber = 1;
        this.state = {
            showAlert: false,
            alertVisible: false,
            visibleSwiper: false,
            onLoadEndImg: false,
            businessModalDialog: false,
            modalVisible: false,
            usersDataLoad: false,
            swap_amount: 0,
            currency_code: '',
            dataSource: ds,
            goodsInfo: this.props.goodsInfo,
            childrenData: null,
            attrsData: null,
            userData: null,
            country: '',
            usersData: [],

            isAddToCart: true,

            promoteDay: '00',
            promoteHour: '00',
            promoteMin: '00',
            promoteSec: '00',
            promoteEntTime: '00:00:00',
        };

    }


    componentDidMount() {
        CommonUtils.getAcyncInfo('getPv')
            .then((result) => {
                if (result) {
                    let parse = JSON.parse(result);
                    this.setState({

                        country: parse.region_id,
                        swap_amount: parse.swap_amount,
                        currency_code: parse.currency_code,
                    })
                }
            });


        CommonUtils.getAcyncInfo('userInfo')
            .then((userData) => {
                this.setState({
                    userData: JSON.parse(userData)
                })
            });


        this.deEmitterUserData = DeviceEventEmitter.addListener('upDateUserData', (userData) => {
            if (userData && userData !== this.state.userData) {
                this.setState({
                    userData: userData,
                });
            }
        });

        // let goodsInfo = this.props.goodsInfo;
        // if (goodsInfo) {
        // 	this.onLoadData(goodsInfo.country)
        // } else {
        // 	CommonUtils.getAcyncInfo('country_iso')
        // 		.then((result) => {
        // 			this.onLoadData(result)
        // 		})
        // }

        CommonUtils.getAcyncInfo('country_iso')
            .then((result) => {
                this.country = result;
                this.onLoadData(result)
            });

        this.startPromoteTime(this.props.goodsInfo)


    }

    componentWillUnmount() {
        this.timeout && clearTimeout(this.timeout);
        this.promoteTimer && clearInterval(this.promoteTimer);
        this.promoteTimer = null;

        this.deEmitterUserData && this.deEmitterUserData.remove();
    }

    /**
     * 获取产品的信息
     */
    onLoadData(country) {
        let goodsInfo = this.props.goodsInfo;
        let goodsId;
        if (this.props.goods_id) {
            goodsId = this.props.goods_id;
            CommonUtils.showLoading();
        } else {
            goodsId = goodsInfo.product_id
        }

        this.iparNetwork.getRequest(SERVER_TYPE.uiAdminIpar + 'product?',
            'country=' + country + '&id=' + goodsId)
            .then((result) => {
                console.log(result);
                if (result.code === 200) {
                    this.startPromoteTime(result.data);
                    this.setState({
                        goodsInfo: result.data,
                        dataSource: this.state.dataSource.cloneWithRows(result.data.goods),
                        childrenData: result.data.children,
                        attrsData: result.data.attrs,
                        visibleSwiper: true,
                    });
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));

                }
                CommonUtils.dismissLoading();

            })
            .catch((error) => {
                CommonUtils.dismissLoading();

                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                console.log('GoodsPage--componentDidMount--error: ', error)
            })
    }


    /**
     * 产品收藏
     */
    onClickCollection() {
        let goodsInfo = this.state.goodsInfo;
        if (!goodsInfo) {
            return;
        }
        let userData = this.state.userData;
        if (!userData) {
            this.startLogin();
            return;
        }

        CommonUtils.showLoading();


        let formData = new FormData();
        formData.append('type', 2);
        formData.append('obj_id', goodsInfo.product_id);
        formData.append('country', this.country);
        formData.append('user_id', userData.main_user_id);
        formData.append('title', this._goodsName);
        formData.append('image', goodsInfo.image);


        this.iparNetwork.getPostFrom(SERVER_TYPE.adminIpar + 'saveCollection', formData)
            .then((result) => {
                CommonUtils.dismissLoading();

                if (result.code === 200) {
                    DeviceEventEmitter.emit('toast', I18n.t('default.success'));
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                }


            })
            .catch((error) => {
                CommonUtils.dismissLoading();

                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                console.log('GoodsPage----onClickCollection--', error)
            })
    }

    _renderRow(rowData, index) {
        return (
            <GoodsRender
                key={index}
                dataSource={rowData}
                navigator={this.props.navigator}
            />
        );
    }

    /**
     * 获取子账号
     */
    onLoadUsersData() {

        let userId = this.state.userData ? this.state.userData.main_user_id : '';

        this.iparNetwork.getRequest(SERVER_TYPE.admin + 'getSubAccount?', 'main_user_id=' + userId)
            .then((result) => {
                if (result.code === 200) {
                    this.setState({
                        usersDataLoad: false,
                        usersData: result.data,
                    })
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                    this.setState({
                        usersDataLoad: false,
                    });
                }

            })
            .catch((error) => {
                this.setState({
                    usersDataLoad: false,
                });

                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                console.log('MatrixPlanPage-----onLoadData--error: ', error);
            })
    }

    /**
     * 初始化(init)
     * */
    render() {

        /**
         * 临时
         * @type {string}
         */

        let renderConfig = this.getParallaxRenderConfig();

        let goodsInfo = this.state.goodsInfo;

        let state = this.state;
        return (
            <View style={StyleUtils.flex}>

                <ParallaxScrollView
                    contentBackgroundColor={'white'}
                    backgroundColor={'white'}
                    parallaxHeaderHeight={PARALLAX_HEADER_HEIGHT}
                    stickyHeaderHeight={STICKY_HEADER_HEIGHT}
                    backgroundSpeed={10}
                    {...renderConfig}
                >

                    {this.renderContent()}

                </ParallaxScrollView>
                {goodsInfo && goodsInfo.num > goodsInfo.auto_off &&
                <View style={[styles.btnBox, StyleUtils.rowDirection]}>
                    {ViewUtils.getButton(I18n.t('b.autoOrder'), () => this.addToCart(false), {
                        flex: 1,
                        backgroundColor: 'gray'
                    })}
                    {ViewUtils.getButton(I18n.t('default.addToCart'), () => this.addToCart(true), {flex: 1})}
                </View>}

                <ModalBottomUtils
                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.usersDataLoad}
                            onRefresh={() => this.onLoadUsersData()}
                        />
                    }
                    visible={state.businessModalDialog}
                    dataSource={ds.cloneWithRows(state.usersData)}
                    requestClose={() => this.setState({
                        businessModalDialog: false,
                    })}
                    renderRow={(rowData, sectionID, rowID) => this.modalRow(rowData, rowID)}
                    title={I18n.t('b.businessCenter')}
                />

            </View>

        )
    }

    modalRow(rowData, index) {
        return (<TouchableOpacity
            onPress={() => {
                if (rowData.user_id == rowData.main_user_id) {
                    DeviceEventEmitter.emit('toast', I18n.t('b.selectDefaultBusiness'))
                } else {
                    this.setState({
                        businessModalDialog: false,
                        userData: rowData,
                    });
                    DeviceEventEmitter.emit('upDateUserData', rowData)
                }
            }}
            style={[StyleUtils.flex, StyleUtils.justifySpace]}>
            <Text
                style={[StyleUtils.text, StyleUtils.smallFont, {color: 'black'}]}>{rowData.user_rank ? rowData.user_rank.rank_name : ''}</Text>
            <Text style={[StyleUtils.text, StyleUtils.smallFont, {color: 'black'}]}>{rowData.rand_id}</Text>
        </TouchableOpacity>)
    }

    /**
     * 购买点击
     */
    addToCart(isAddToCart) {
        let userData = this.state.userData;
        if (userData) {
            if (userData.user_id === userData.main_user_id && userData.open_plan_num > 1) { //TA用的是不是主账号
                DeviceEventEmitter.emit('toast', I18n.t('b.selectDefaultBusiness'));
                this.props.navigator.push({
                    component: SubAccountsPage,
                    name: 'SubAccountsPage',
                    params: {userId: userData.main_user_id},
                });
            } else {
                this.main_user_id = userData.main_user_id;
                this.setState({
                    modalVisible: true,
                    isAddToCart: isAddToCart
                })
            }
        } else {
            this.startLogin()
        }


    }


    startLogin() {
        this.props.navigator.push({
            component: LoginPage,
            name: 'LoginPage',
        })
    }

    onModalBtnClick(goodsNumber) {
        this.goodsNumber = goodsNumber;

        if (this.state.isAddToCart) {
            this.setState({
                modalVisible: false,
                showAlert: true,
            })
        } else {
            this.setState({
                modalVisible: false,
            });
            this.submit(false)
        }
    }


    /**
     *
     */
    getVipPrice(goodsInfo) {
        let userData = this.state.userData;
        if (!userData) return null;
        let userLevel = userData.user_level;
        if (!userLevel) return null;
        if (!goodsInfo) return null;
        let swapAmount = this.state.swap_amount;

        // let _vipPrice = new CommonUtils().getPercentOwnAmount(goodsInfo, swapAmount, userData);

        let _vipPrice = new CommonUtils().getNewVipPrice(userData, goodsInfo, swapAmount);

        if (_vipPrice <= 0) return null;


        return (<View style={[StyleUtils.rowDirection, StyleUtils.center]}>
            <Text style={[styles.goodsImageTitle, StyleUtils.smallFont, {marginTop: 8, minWidth: 10}]}>
                {userLevel.level_name} :
            </Text>
            <Text style={[{marginTop: 8, fontSize: 16, marginLeft: 8, minWidth: 10}]}>
                {((_vipPrice).toFixed(0)) + ' ' + this.state.currency_code}
            </Text>
        </View>);
    }


    /**
     * add to card
     * */
    submit(lop) {
        this.setState({
            showAlert: false,
        });

        CommonUtils.showLoading();


        if (this.state.isAddToCart) {
            this.goodsAddToCart(lop)
        } else {
            this.goodsAddToAutoOrder()
        }
    }


    /**
     * 把产品添加到自动订单列表
     */
    goodsAddToAutoOrder() {
        let goodsInfo = this.state.goodsInfo;
        let formData = new FormData();
        let userData = this.state.userData;
        formData.append('user_id', userData.user_id);
        formData.append('main_user_id', userData.main_user_id);
        formData.append('goods_id', goodsInfo.goods_id);
        formData.append('product_id', goodsInfo.product_id);
        formData.append('goods_number', this.goodsNumber);
        this.iparNetwork.getPostFrom(SERVER_TYPE.adminIpar + 'saveAutoOrders', formData)
            .then((result) => {
                if (result.code === 200) {
                    let navigator = this.props.navigator;
                    DeviceEventEmitter.emit('toast', I18n.t('default.success'));
                    navigator.pop()
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                }
            })
            .catch((error) => {
                CommonUtils.dismissLoading();

                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                console.log('GoodsPage--goodsAddToAutoOrder-error: ', error)
            })
    }


    /**
     * 把产品添加到购物车
     * @param lop
     */
    goodsAddToCart(lop) {
        let dataSource = this.state.goodsInfo;
        let userData = this.state.userData;

        let formData = new FormData();

        //isGlobal 的话 3
        let isGlobal = 2;
        if (dataSource.is_global === 1 && (dataSource.global_country && dataSource.global_country.indexOf(this.country) !== -1)) {
            isGlobal = 3;
        }

        formData.append('type', isGlobal);
        formData.append('country', this.state.goodsInfo.country);
        formData.append('product_id', dataSource.product_id);
        formData.append('goods_number', this.goodsNumber);
        formData.append('user_id', userData.user_id);
        formData.append('main_user_id', userData.main_user_id);
        formData.append('number_id', dataSource.number_id);
        formData.append('is_suite', dataSource.is_suite);
        formData.append('items', dataSource.items);


        this.iparNetwork.getPostFrom(SERVER_TYPE.adminIpar + 'addCart', formData)
            .then((result) => {

                let navigator = this.props.navigator;
                CommonUtils.dismissLoading();

                if (result.code === 200) {
                    DeviceEventEmitter.emit('isBuyGoods');
                    if (lop) {
                        navigator.pop()
                    } else {
                        DeviceEventEmitter.emit('goToPage', 3);
                        navigator.popToTop();
                    }
                } else if (result.code === 504) {
                    this.setState({
                        alertVisible: true,
                    });
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                }

            })
            .catch((error) => {
                CommonUtils.dismissLoading();

                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));

                console.log('GoodsPage--goodsAddToCart-error: ', error)
            })
    }


    renderPromoteView(time) {
        return <View style={{borderRadius: 4, backgroundColor: 'black', padding: 4}}>
            <Text style={{color: 'white'}}>{time}</Text>
        </View>
    }

    /**
     *倒计时
     **/
    startPromoteTime(data) {
        if (this.promoteTimer) {
            // this.promoteTimer && clearInterval(this.promoteTimer);
            // this.promoteTimer = null;
            return;
        }
        if (!data) {
            this.promoteTimer && clearInterval(this.promoteTimer);
            this.promoteTimer = null;

            return;
        }
        if (!data.end_time) {
            this.promoteTimer && clearInterval(this.promoteTimer);
            this.promoteTimer = null;
            return;
        }
        if (data.is_promote !== 1) {
            this.promoteTimer && clearInterval(this.promoteTimer);
            this.promoteTimer = null;
            return;
        }


        this.promoteTimer = setInterval(() => {
            const dateData = this.commonUtils.getDateData(data.end_time);

            let days = dateData.days;
            let promoteDay = getFormatDate(days);
            let hours = dateData.hours;
            let promoteHour = getFormatDate(hours);
            let min = dateData.min;
            let promoteMin = getFormatDate(min);
            let sec = dateData.sec;
            let promoteSec = getFormatDate(sec);


            this.setState({
                // promoteEntTime: promoteDay + " : " + promoteHour + " : " + promoteMin + " : " + promoteSec,
                promoteDay,
                promoteHour,
                promoteMin,
                promoteSec,
            });

            if (days === 0 && hours === 0 && min === 0 && sec === 0) {
                this.promoteTimer && clearInterval(this.promoteTimer);
                this.promoteTimer = null;
            }
        }, 1000);
    }

    /**
     * 中间的items和views
     * */
    renderContent() {

        let state = this.state;
        let goodsInfo = state.goodsInfo;

        let goodsCountryIcon = goodsInfo && goodsInfo.is_global == 1 && new RegionsIcon().getIcons(goodsInfo.country);


        this._goodsName = '';
        let contentHtml = null;


        let _spec = '';
        let vipPrice = null;
        let promote = false;
        if (goodsInfo) {
            _spec = goodsInfo.spec;
            //goods name
            this._goodsName = goodsInfo.goods_local_name;
            contentHtml = goodsInfo.content_for_pc;

            if (state.country === 'CN') {
                if (I18n.locale === 'uy') {
                    this._goodsName = goodsInfo.goods_name;
                    contentHtml = goodsInfo.content_for_mb;
                }
            } else {
                if (I18n.locale !== 'en') {
                    contentHtml = goodsInfo.content_for_mb;
                }

                if (I18n.locale === 'ru') {
                    this._goodsName = goodsInfo.goods_name;
                }
            }

            if (!contentHtml) {
                contentHtml = null;
            }

            let specs = goodsInfo.specs;

            if (specs) {
                _spec = specs.name;
                switch (I18n.locale) {
                    case 'en':
                        _spec = specs.name_en;
                        break;
                    case 'uy':
                        _spec = specs.name_uy;
                        break;
                    case 'ru':
                        _spec = specs.name_ru;
                        break
                }
            }


            vipPrice = this.getVipPrice(goodsInfo);
            promote = goodsInfo.is_promote === 1 && goodsInfo.end_time;

        }

        const renderPromoteCricleView = <View style={{justifyContent: 'space-around', padding: 4}}>
            <View style={{borderRadius: 2, height: 4, width: 4, backgroundColor: 'black'}}/>
            <View style={{borderRadius: 2, height: 4, width: 4, backgroundColor: 'black'}}/>
        </View>


        // const origin_pv = promote ? goodsInfo.origin_pv * this.state.swap_amount : vipPrice;
        return (goodsInfo ?
                <View>
                    <View style={{padding: 16}}>


                        <Text style={[StyleUtils.title, StyleUtils.smallFont, {textAlign: null}]}>
                            {this._goodsName}
                        </Text>


                        <View style={[StyleUtils.justifySpace, {marginTop: 16}]}>
                            <View
                                style={{
                                    backgroundColor: promote ? 'black' : '#f3f3f3',//f33b58
                                    flex: 1,
                                    padding: 8,
                                    paddingTop: 4,
                                    paddingBottom: 4,
                                    height: 64,
                                    justifyContent: 'center',
                                }}>
                                <Text style={{
                                    color: promote ? 'white' : 'black',
                                    fontSize: 12,
                                }}>{I18n.t('default.retailPrice')}</Text>
                                <Text
                                    numberOfLines={1}
                                    style={[{
                                        fontSize: 20,
                                        color: promote ? 'white' : 'black'
                                    }]}>{(goodsInfo.goods_pv * state.swap_amount).toFixed(0) + ' ' + state.currency_code}</Text>

                                {promote && <View style={[StyleUtils.rowDirection]}>
                                    <View style={[{borderRadius: 2, backgroundColor: 'red'}, StyleUtils.center]}>
                                        <Text
                                            numberOfLines={1}
                                            style={[{
                                                fontSize: 8,
                                                color: promote ? 'white' : 'black',
                                                padding: 2,
                                                backgroundColor: 'transparent'
                                            }]}>OFF</Text>
                                    </View>
                                    <Text
                                        numberOfLines={1}
                                        style={[StyleUtils.goodsLineThroughText, {
                                            color: promote ? 'white' : 'black',
                                            marginLeft: 8,
                                            fontSize: 14,

                                        }]}> {(goodsInfo.origin_pv * this.state.swap_amount).toFixed(0) + ' ' + this.state.currency_code}</Text>
                                </View>}
                            </View>

                            {promote && <View style={[{
                                backgroundColor: '#f3f3f3',
                                height: 64,
                                paddingRight: 16,
                                paddingLeft: 16,
                            }, StyleUtils.center]}>

                                <Text
                                    numberOfLines={1}
                                    style={[{
                                        fontSize: 12,
                                        color: 'black',
                                        marginBottom: 6,
                                    }, StyleUtils.smallFont]}>{I18n.t('o.expiresIn')}</Text>

                                <View style={[StyleUtils.rowDirection]}>
                                    {this.renderPromoteView(state.promoteDay)}
                                    {renderPromoteCricleView}
                                    {this.renderPromoteView(state.promoteHour)}
                                    {renderPromoteCricleView}
                                    {this.renderPromoteView(state.promoteMin)}
                                    {renderPromoteCricleView}
                                    {this.renderPromoteView(state.promoteSec)}
                                </View>

                            </View>}

                        </View>


                        {/*{this.state.userData ? <TouchableOpacity*/}
                        {/*onPress={() => {*/}
                        {/*this.setState({*/}
                        {/*businessModalDialog: true,*/}
                        {/*usersDataLoad: true,*/}
                        {/*}, this.onLoadUsersData())*/}
                        {/*}}>*/}
                        {/*<Text style={{*/}
                        {/*marginTop: 8,*/}
                        {/*color: '#999'*/}
                        {/*}}>{I18n.t('b.defaultBC')} {this.state.userData.rand_id}</Text>*/}
                        {/*</TouchableOpacity> : null}*/}


                        {/**报价-价格*/}
                        {this.state.userData != null && this.state.userData.level > 0 &&
                        <View style={[StyleUtils.justifySpace, {
                            width: '100%',
                            alignItems: 'flex-start',
                            paddingTop: goodsInfo.is_promote === 1 ? 20 : 8
                        }]}>
                            {/*<Text*/}
                            {/*numberOfLines={1}*/}
                            {/*style={[styles.goodsImageTitle, StyleUtils.smallFont]}>SALE</Text>*/}
                            {/*{goodsInfo.is_promote === 1 ?*/}
                            {/*    <Text style={[StyleUtils.title, StyleUtils.smallFont, {*/}
                            {/*        paddingLeft: 16,*/}
                            {/*        color: '#b5b5b5'*/}
                            {/*    }]}>*/}
                            {/*        {(goodsInfo.origin_pv * this.state.swap_amount).toFixed(0) + ' ' + this.state.currency_code}*/}
                            {/*    </Text> : null}*/}


                            <Text style={[StyleUtils.title, StyleUtils.smallFont, {
                                marginRight: 8,
                                fontSize: 16,
                                color: '#b5b5b5',
                                fontWeight: ('bold', '900'),
                            }]}>
                                {"PV " +
                                (goodsInfo.goods_bv ? goodsInfo.goods_bv.toFixed(2) : '0' + 'BV')}
                            </Text>
                        </View>}


                        <View style={[StyleUtils.rowDirection]}>
                            {this.getVipPrice(goodsInfo)}
                        </View>

                        <Text style={[styles.goodsMinContent, StyleUtils.smallFont, {marginTop: 16}]}>
                            {I18n.t('default._no') + ' : ' + goodsInfo.goods_code}
                        </Text>
                        <Text style={[styles.goodsMinContent, StyleUtils.smallFont]}>
                            {I18n.t('default.weight') + ' : ' + goodsInfo.weight} G
                        </Text>
                        <Text style={[styles.goodsMinContent, StyleUtils.smallFont]}>
                            {I18n.t('default.specification') + ' : ' + _spec}
                        </Text>


                        {/**country name*/}
                        {goodsInfo.is_global == 1 && goodsInfo.country !== this.country &&

                        <View style={[StyleUtils.rowDirection, {alignItems: 'center', marginTop: 16}]}>
                            <Image
                                resizeMode="contain"
                                style={{resizeMode: 'contain', height: 12, width: 20}}
                                source={goodsCountryIcon}/>
                            <Text
                                numberOfLines={1}
                                style={[styles.countryName, StyleUtils.smallFont]}>{this.countryGoods(goodsInfo.country)} </Text>
                        </View>}


                        {/**HTML View*/}
                        {contentHtml && <MyWebView
                            startInLoadingState={true}
                            defaultHeight={50}
                            style={{width: width - 30, marginTop: 20}}
                            source={{
                                html: contentHtml + "<style>\n" +
                                    "    img{\n" +
                                    "        width: 100%;\n" +
                                    "    }\n" +
                                    "</style>"
                            }}
                            scalesPageToFit={true}
                        />}

                        {/*</View>*/}
                    </View>


                    {/**推荐产品*/}
                    <ListView
                        enableEmptySections={true}
                        style={{marginBottom: 100,}}
                        pageSize={1}
                        dataSource={state.dataSource}
                        contentContainerStyle={styles.gridListStyle}
                        renderRow={(rowData, s, index) => this._renderRow(rowData, index)}/>


                    <AddToCartModal
                        isAddToCart={state.isAddToCart}
                        onRequestClose={() => {
                            this.setState({
                                modalVisible: false,
                            })
                        }}
                        childrenData={state.childrenData}
                        attrsData={state.attrsData}
                        updateProduct={(product) => {
                            if (this.state.goodsInfo !== product) {
                                this.setState({
                                    goodsInfo: product
                                })
                            }
                        }}
                        submit={(goodsNumber) => this.onModalBtnClick(goodsNumber)}
                        navigator={this.props.navigator}
                        dataSource={state.goodsInfo}
                        visible={state.modalVisible}/>

                    <AlertDialog
                        contentTv={I18n.t('default.addedToCart')}
                        visible={state.showAlert}
                        leftBtnOnclick={() => this.submit(true)}
                        rightBtnOnclick={() => this.submit(false)}
                        leftSts={I18n.t('default.keepShopping')}
                        rightSts={I18n.t('default.payNow')}
                        requestClose={() => this.setState({showAlert: false})}/>


                    <AlertDialog
                        requestClose={() => {
                            this.setState({
                                alertVisible: false,
                            })
                            this.props.navigator.pop();
                        }}
                        visible={state.alertVisible}
                        centerIcon={require('../../res/ic_sold_out.png')}
                        contentTv={I18n.t('o.soldOut')}
                        centerSts={'ok'}
                        singleBtnOnclick={() => {
                            this.setState({
                                alertVisible: false,
                            })
                        }}/>

                </View> : null
        )

    }

    headresImageItems(image, index) {
        {/*<Image*/
        }
        {/*    key={index}*/
        }
        {/*    onLoadEnd={() => {*/
        }
        {/*        this.setState({onLoadEndImg: true})*/
        }
        {/*    }}*/
        }
        {/*    style={styles.headerImages}*/
        }
        {/*    source={image.img_url ? {uri: IMAGE_URL + image.img_url} :*/
        }
        {/*        require('../../res/images/ic_image_fail.png')}/>*/
        }
        return <IparImageView
            key={index}
            onLoadEnd={() => this.setState({onLoadEndImg: true})} width={width} height={width}
            url={image.img_url}/>

    }

    /*从xxx国家发货*/
    countryGoods(name) {
        let goodsCountry;
        switch (name) {
            case 'RU':
                goodsCountry = I18n.t('default.shippedFromIpar') + ' Russia';
                break;
            case 'CN':
                goodsCountry = I18n.t('default.shippedFromIpar') + ' China';
                break;
            case 'KZ':
                goodsCountry = I18n.t('default.shippedFromIpar') + ' Kazakhstan';
                break;
            case 'US':
                goodsCountry = I18n.t('default.shippedFromIpar') + ' United States';
                break;
            case 'KG':
                goodsCountry = I18n.t('default.shippedFromIpar') + ' Kyrgyzstan';
                break;
            case 'AZ':
                goodsCountry = I18n.t('default.shippedFromIpar') + ' Azerbaijan';
                break;
            default:
                goodsCountry = name;
                break
        }
        return goodsCountry;
    }


    /***
     * render Parallax content
     */
    getParallaxRenderConfig() {
        let goodsInfo = this.state.goodsInfo;
        let config = {};

        /**headers image*/
        if (goodsInfo) {

            let headresImage = (<View
                style={styles.headerImages}>
                {!this.state.onLoadEndImg &&
                <IparImageView
                    // onLoadEnd={() => this.setState({onLoadEndImg: true})}
                    width={width}
                    height={width}
                    url={goodsInfo.image}/>}


                {this.state.visibleSwiper && goodsInfo.topImg && goodsInfo.topImg.length > 0 &&
                <Carousel
                    autoplay={this.state.onLoadEndImg}
                    autoplayTimeout={2000}
                    loop={this.state.onLoadEndImg}
                    index={0}
                    showsPageIndicator={false}>
                    {goodsInfo.topImg.map((image, index) => this.headresImageItems(image, index))}
                </Carousel>
                }

                {/*soldOut*/}
                {/*{goodsInfo.num <= goodsInfo.auto_off && <View style={[styles.soldOutStyle, StyleUtils.center]}>*/}
                {/*    <Image*/}
                {/*        style={{width: 50, height: 50}}*/}
                {/*        source={require('../../res/ic_sold_out.png')}/>*/}
                {/*    <Text style={[{fontSize: 18, color: 'white'}, StyleUtils.smallFont]}>{I18n.t('o.soldOut')}</Text>*/}
                {/*</View>}*/}
            </View>);


            /**
             * 产品图片---header
             * @type {{}}
             */
            config.renderBackground = () => (
                <View key="background">
                    <View style={{height: width}}>
                        {headresImage}
                    </View>
                </View>
            );
        }
        /**
         * toolbar title
         * @type {{}}
         */
        config.renderStickyHeader = () => (
            <View key="sticky-header" style={styles.stickySection}>
                <Text
                    numberOfLines={1}
                    style={[StyleUtils.title, StyleUtils.smallFont, {
                        marginLeft: navigationSize,
                        marginRight: navigationSize
                    }]}>
                    {this._goodsName}
                </Text>
            </View>
        );

        /**
         * toolbar icons
         * @type {{}}
         */
        config.renderFixedHeader = () => (
            <View key="fixed-header" style={styles.fixedSection}>
                {ViewUtils.getImageBtnView([StyleUtils.center, styles.navBtn],
                    require('../../res/images/ic_back.png'), StyleUtils.tabIconSize, () => {
                        this.props.navigator.pop()
                    })}
                {ViewUtils.getImageBtnView([StyleUtils.center, styles.navBtn],
                    require('../../res/images/ic_collection.png'), StyleUtils.tabIconSize, () => this.onClickCollection())}
            </View>
        );
        return config;
    }


}

/**
 * ParallaxScrollView 的toolbar尺寸
 */
const navigationSize = Platform.OS === 'ios' ? 40 : 50;//NAV 的大小
const PARALLAX_HEADER_HEIGHT = width;
const STICKY_HEADER_HEIGHT = navigationSize;

const styles = StyleSheet.create({
    headerImages: {
        width: width,
        height: width,
    },
    goodsImageTitle: {
        backgroundColor: '#ff6056',
        padding: 4,
        fontSize: 16,
        color: 'white'
    },
    navBtn: {
        width: navigationSize,
        height: navigationSize,
    },

    goodsMinContent: {
        color: '#343434',
        marginTop: 8,
        fontSize: 14
    },

    btnBox: {
        padding: 16,
        paddingTop: 0,
        backgroundColor: 'rgba(255, 255, 255, 0.88)',
        position: 'absolute',
        left: 0,
        right: 0,
        bottom: 0
    },
    gridListStyle: {
        flexDirection: 'row',
        flexWrap: 'wrap'
    },

    stickySection: {
        height: STICKY_HEADER_HEIGHT,
        justifyContent: 'center',
        alignItems: 'center',
    },

    fixedSection: {
        position: 'absolute',
        left: 0,
        right: 0,
        top: 0,
        bottom: 0,
        paddingRight: 8,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
    },
    countryName: {
        padding: 8,
        fontSize: 12,
        color: '#898b8d'
    },


    soldOutStyle: {
        position: 'absolute',
        left: 0,
        right: 0,
        top: 0,
        bottom: 0,
        backgroundColor: 'rgba(0,0,0,0.32)'
    },
});
